package com.moliku.insurance.process.service.impl;



import com.moliku.insurance.common.response.CommonInsureResult;
import com.moliku.insurance.common.util.AesUtil;
import com.moliku.insurance.model.dto.CancelInsureDTO;
import com.moliku.insurance.model.dto.DownloadInsureDTO;
import com.moliku.insurance.model.dto.insure.InsureDTO;
import com.moliku.insurance.model.entity.ChongQing.*;
import com.moliku.insurance.process.strategy.PolicyStrategy;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 重庆人保
 *
 * @author Mr.Liu
 * @since 2021/2/5
 */
@Slf4j
@AllArgsConstructor
@Service("CqPiccService")
public class CqPiccServiceImpl implements PolicyStrategy {

    private static final String SUBMIT_POLICY_URL = "https://partnertest.mypicc.com.cn/ecooperation/webrequest/insure.do?plateformcode=CPI000248&riskcode=EAU";

    private final RestTemplate restTemplate;


    @SneakyThrows
    @Override
    public CommonInsureResult submitPolicy(InsureDTO request) {

        GeneralInfo generalInfo = new GeneralInfo();
        generalInfo.setUUID("baoyou"+request.getOrder().getSerialNumber());
        //暂时写死
        generalInfo.setPlateformCode("CPI000001");
        //String sign=generalInfo.getUUID()+request.getOrder().getPremium()+"Picc37mu63ht38mw";
        //String md5Value = DigestUtils.md5Hex(sign.getBytes(StandardCharsets.UTF_8));
       // generalInfo.setMd5Value(md5Value);

        ArrayList<PolicyInfo> policyInfoArrayList=insuranceInformation(request);

        ApplyInfo policyInfos = new ApplyInfo();
        policyInfos.setPolicyInfo(policyInfoArrayList);
        policyInfos.setGeneralInfo(generalInfo);
        JAXBContext  context = JAXBContext.newInstance(ApplyInfo.class);
        String encrypt=beanToXml(policyInfos,context);

        //测试Http数据请求与响应
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("text/xml;charset=UTF-8"));
        HttpEntity<String> httpEntity = new HttpEntity<>(encrypt, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(SUBMIT_POLICY_URL, httpEntity, String.class);
        log.info("响应：{}", entity);
        return CommonInsureResult.submitPolicyFail("重庆人保投保尚未接通");
    }

    @Override
    public CommonInsureResult cancelPolicy(CancelInsureDTO request) {
        return CommonInsureResult.cancelPolicyFail("重庆人保退保尚未接通");
    }

    @Override
    public CommonInsureResult downloadPolicy(DownloadInsureDTO downloadInsure) {
        return CommonInsureResult.downloadPolicyFail("重庆人保下载保单尚未接通");
    }


    /**
     * 投保信息
    */
    public ArrayList<PolicyInfo> insuranceInformation(InsureDTO request) {
        try {
        PolicyInfo policyInfo = new PolicyInfo();
        policyInfo.setSerialNo("1");
        policyInfo.setRiskCode("");
        policyInfo.setOperateTimes(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        policyInfo.setStartDate(request.getOrder().getStartTime().substring(0,10));

        policyInfo.setEndDate(request.getOrder().getEndTime().substring(0,10));
        policyInfo.setStartHour("0");
        policyInfo.setEndHour("24");



        InsuredPlan insuredPlan = new InsuredPlan();
        insuredPlan.setRationType("");

        Applicant applicant = new Applicant();
        applicant.setAppliName(request.getPolicyHolder().getcName());
        String sex="";
        if (StringUtils.isNotBlank(request.getPolicyHolder().getSex())){
             sex="1".equals(request.getPolicyHolder().getSex())?"1":"2";
        }
        applicant.setAppliSex(sex);
        applicant.setAppliIdType(request.getPolicyHolder().getCardType());
        applicant.setAppliIdNo(request.getPolicyHolder().getCardNo());
        applicant.setAppliIdMobile(request.getPolicyHolder().getMobile());
        //暂时写死
        applicant.setSendSMS("N");
        applicant.setAppliIdEmail(request.getPolicyHolder().getEmail());

        //暂时写死
        applicant.setAppliIdentity("0");

        Linker linker = new Linker();
        linker.setLinkerName("");
        linker.setLinkerPhone("");

        List<Insured> insuredList = new ArrayList<>();
        for (int i = 0; i < request.getInsureds().size(); i++) {
            Insured insured = new Insured();
            insured.setInsuredSeqNo("0");
            insured.setInsuredName(request.getInsureds().get(i).getCName());
            //insured.setInsuredIdentity(request.getInsureds().get(i).getRelation());
            insured.setInsuredIdType(request.getInsureds().get(i).getCardType());
            insured.setInsuredIdNo(request.getInsureds().get(i).getCardNo());
            sex="1".equals(request.getInsureds().get(i).getSex())?"1":"2";
            insured.setInsuredSex(sex);
            insuredList.add(insured);
        }

        policyInfo.setInsured(insuredList);
        policyInfo.setApplicant(applicant);
        policyInfo.setInsuredPlan(insuredPlan);
        policyInfo.setLinker(linker);

        ArrayList<PolicyInfo> policyInfoArrayList = new ArrayList<>();
        policyInfoArrayList.add(policyInfo);
        return policyInfoArrayList;
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }

    /**
     * bean转xml
    */
    private String beanToXml(ApplyInfo applyInfo,JAXBContext context){
        String encrypt="";
        try {
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "GB2312");

            String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xml";
            FileWriter writer = new FileWriter(new File("D://" + date));
            marshaller.marshal(applyInfo, writer);
            File f = new File("D://" + date);
            BufferedReader reader;
            StringBuilder sbf = new StringBuilder();
            reader = new BufferedReader(new FileReader(f));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            log.info("acs加密前：{}", sbf.toString());
             encrypt = AesUtil.encryptBase64("4BC69F15A8740F1F4F5C775F5EEB7B6D", sbf.toString());
            log.info("请求：{}", encrypt);
        }catch (Exception e){
            e.printStackTrace();
        }
        return encrypt;

    }



}
